package com.lzscale.scalelib.misclib;

import android.util.Log;

import java.io.UnsupportedEncodingException;

public class SPrinter extends AbstractPrinter {

    private static final String DEBUG = SPrinter.class.getSimpleName();

    public SPrinter() {
        super("dev/ttymxc1");
    }

    public void expand(int ex, int ey) {
        byte[] b = {0x1d, 0x21, 0x00};
        if (ex > 1 && ex <= 8)
            b[2] |= ((ex - 1) << 4);
        if (ey > 1 && ey <= 8)
            b[2] |= (ex - 1);
        mPort.send(b);
    }

    public void printQRCode(final String content, int size, CorrectionLevel level) {
        printQRCode(content.getBytes(), size, level);
    }

    private void printQRCode(byte[] content, int size, CorrectionLevel level) {
        byte[] ba = {0x1d, 0x28, 0x6b, 0x03, 0x00, 0x31, 0x43, 0x00};
        ba[ba.length - 1] = (byte) (size);
        mPort.send(ba);
        ba[ba.length - 2] = 0x45;
        switch (level) {
            case CORRECTION_L:
                ba[ba.length - 1] = '0';
                break;
            case CORRECTION_M:
                ba[ba.length - 1] = '1';
                break;
            case CORRECTION_Q:
                ba[ba.length - 1] = '2';
                break;
            case CORRECTION_H:
                ba[ba.length - 1] = '3';
                break;
        }
        mPort.send(ba);
        ba[3] = (byte) ((content.length + 3) & 0xff);
        ba[4] = (byte) ((content.length + 3) >> 8);
        ba[ba.length - 2] = 0x50;
        ba[ba.length - 1] = '0';
        mPort.send(ba);
        mPort.send(content);
        ba[3] = 0x03;
        ba[4] = 0x00;
        ba[ba.length - 2] = 0x51;
        mPort.send(ba);
    }    @Override
    public void print(byte[] bs) {
        mPort.send(bs);
    }

    @Override
    protected void finalize() {
        if (mPort != null) {
            try {
                mPort.finalize();
            } catch (Exception e) {
                Log.e(DEBUG, e.getMessage());
            }
        }
    }

    public enum CorrectionLevel {
        CORRECTION_L, CORRECTION_M, CORRECTION_Q, CORRECTION_H
    }

    @Override
    public void print(String txt) {
        try {
            byte[] bs = txt.getBytes("GBK");
            this.print(bs);
        } catch (UnsupportedEncodingException e) {
            Log.e(DEBUG, e.getMessage());
        }
    }




}
